package com.abxh.ffmpage;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Size;
import android.widget.Toast;

import com.abxh.core.utils.LogUtils;
import com.abxh.jetpack.base.BaseViewModelActivity;
import com.google.common.util.concurrent.ListenableFuture;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * Created by dab on 2021/9/5 17:02
 */

public class FFmpageActivity extends BaseViewModelActivity<AvViewModel> {
    private ProcessCameraProvider mProcessCameraProvider;
    private Size resolution = new Size(480, 640);
//    static {
//        System.loadLibrary("native-lib");
//    }
//
//    private native String stringFromJNI();
//
//    private native String ffmpegInfo();


    @SuppressLint("MissingSuperCall")
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ffmpage_activity_main);

//        LogUtils.e("onCreate*****: " + stringFromJNI());
//        LogUtils.e("onCreate*****: " + ffmpegInfo());
//        MediaCodec codec = MediaCodec.createByCodecName("video/avc");
        getPermission();
        findViewById(R.id.btn_takePhoto).setOnClickListener(v -> {
            takePhoto();
        });
    }

    private void initCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                mProcessCameraProvider = cameraProviderFuture.get();
                bindPreview(mProcessCameraProvider, findViewById(R.id.pv_content));
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }, ContextCompat.getMainExecutor(this));
    }

    private void bindPreview(ProcessCameraProvider processCameraProvider, PreviewView previewView) {
        viewModel.start(resolution);
        Preview preview = new Preview.Builder().setTargetResolution(resolution).build();
        CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
        processCameraProvider.unbindAll();
        preview.setSurfaceProvider(previewView.getSurfaceProvider());
        Camera camera = processCameraProvider.bindToLifecycle(this, cameraSelector, preview, getAnalysis());
    }

    //Analysis和Priview中设置的分辨率可以不同，这说明分析图片和预览图片是可以分开应用的。
    private ImageAnalysis getAnalysis() {
        ImageAnalysis imageAnalysis = new ImageAnalysis.Builder().build();
        imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this),
                new ImageAnalysis.Analyzer() {
                    @Override
                    public void analyze(@NonNull ImageProxy image) {

//                        ImageProxy.PlaneProxy[] planes = image.getPlanes();
//                        int length = planes.length;
//                        if (length > 2) {
//                            LogUtils.e("analyze*****: " + planes[0].getPixelStride() + planes[1].getPixelStride() + planes[2].getPixelStride());
//                        }
                        viewModel.put(image);
//                        LogUtils.e("analyze*****: " + length);
//                        LogUtils.e("analyze*****: " + image.getImageInfo().toString());
//                        image.close();
                    }
                }
        );
        return imageAnalysis;
    }


    private void takePhoto() {
        if (mProcessCameraProvider == null) {
            return;
        }
        ImageCapture imageCapture = new ImageCapture.Builder()
                //优化捕获速度，可能降低图片质量
                .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                //设置宽高比
                .setTargetResolution(new Size(640, 480))
                //设置初始的旋转角度
                .build();
        String dirPath = getExternalFilesDir("").getAbsolutePath()
                + File.separator + "TestRecode";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            boolean mkdir = dirFile.mkdir();
            LogUtils.e("takePhoto: mkdir：" + mkdir);
        }
        File file = new File(dirFile, System.currentTimeMillis() + ".jpg");
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
                LogUtils.e("takePhoto: newFile：" + newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(file).build();
        mProcessCameraProvider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, imageCapture);
        imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
            @Override
            public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                Uri savedUri = outputFileResults.getSavedUri();
                if (savedUri == null) {
                    savedUri = Uri.fromFile(file);
                }
                LogUtils.e("onImageSaved*****: " + file.getAbsolutePath());
                LogUtils.e("onImageSaved*****: " + file.length());
                Toast.makeText(FFmpageActivity.this, savedUri.getPath(), Toast.LENGTH_SHORT).show();
                mProcessCameraProvider.unbind(imageCapture);
            }

            @Override
            public void onError(@NonNull ImageCaptureException exception) {
                exception.printStackTrace();
            }
        });
    }


    /**
     * 获取权限
     */
    private void getPermission() {
        if (Build.VERSION.SDK_INT > 22) {
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //先判断有没有权限 ，没有就在这里进行权限的申请
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x86);
                initCamera();
            } else {
                initCamera();
            }
        } else {
            initCamera();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x86 && resultCode == RESULT_OK) {
            initCamera();
        } else {
            finish();
        }
    }
}
